<!-- ----------------------------
--  @author: 野狼上校           --
--  @create: 2024-04-03 11:45  --
--  @version: 1.0              --
-------------------------------->
<!-- 登录 -->
<template>
  <div class="login-div">
    <el-form
        ref="loginFormRef"
        style="max-width: 600px"
        :model="loginForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="loginForm-box"
    >
      <el-form-item label="手机" prop="phone">
        <el-input v-model="loginForm.phone" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" type="password" autocomplete="off"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="login-button" @click="submitForm(loginFormRef)">登录</el-button>
      </el-form-item>
    </el-form>
  </div>

</template>

<script setup lang="ts">
import {reactive, ref} from "vue";
import {ElMessage, FormInstance, FormRules} from "element-plus";
import {validatorPassword, validatorUsername} from "@/validator";
import {SUCCESS} from "@/utils/constants.ts";
import router from "@/router";
import {loginInfo} from "@/api/auth/user.ts";
import {userStore} from "@/pinia/auth/userPinia.ts";
import {RespResult} from "@/api";

// 表单引用
const loginFormRef = ref<FormInstance>()
// 登录表单
const loginForm = reactive({
  phone: '15874609836',
  password: '123456',
})

// 表单验证规则
const rules = reactive<FormRules<typeof loginForm>>({
  phone: [{validator: validatorUsername, trigger: 'blur'}],
  password: [{validator: validatorPassword, trigger: 'blur'}],
})

// 提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // 发送请求
      loginInfo(JSON.stringify(loginForm)).then(
          (response: RespResult) => {
            if (response.code === SUCCESS) {  // 成功
              ElMessage({
                message: "登录成功",
                type: "success"
              })

              userStore().setToken(response.data.token);
              userStore().setUserInfo(response.data.userInfo);

              // 页面跳转
              router.push("/home");
            } else {  // 失败
              ElMessage({
                message: "失败原因: " + response.message,
                type: 'error'
              })
            }
          }
      )
    } else {
      // 表单验证不通过
      return false
    }
  })
}

</script>

<style scoped>
.login-div {
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 320px;
  min-height: 100vh;
}

/* 登录的div */
.loginForm-box {
  padding: 30px 40px 10px 40px;
  border: 1px solid #1a1a1a;
}

/* 登录按纽*/
.login-button {
  width: 100%;
}
</style>